from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from myadmin.models import Category, Shop
from django.db.models import Q
from django.core.paginator import Paginator
from datetime import datetime


# 菜品类别信息管理的视图文件
# Create your views here.

def index(request, pIndex=1):  # 浏览信息
    umod = Category.objects
    # 将已删除的店铺的菜品分类删除
    shop = Shop.objects.filter(status=9)
    ulist = umod.filter(status__lt=9)
    for i in shop:
        for j in ulist:
            if i.id == j.shop_id:
                print(1111)
                j.shop_id = str(j.shop_id)
                j.status = 9
                j.save()
    ulist = umod.filter(status__lt=9)
    ulist = ulist.order_by("id")  # 对id排序
    # 获取并判断搜索条件
    mywhere = []
    kw = request.GET.get("keyword", None)
    if kw:
        wk = []
        shop = Shop.objects.filter(Q(name__contains=kw) & Q(status__lt=9))
        for a in shop:
            wk.append(a.id)
        cc = 'ulist.filter(Q(name__contains=kw)'  # 从定义shop_id与店铺名称的关系
        for i in range(len(wk)):
            cc = cc + ' | Q(shop_id=wk[{}])'.format(i)
        cc = cc + ')'
        ulist = eval(cc)
        print(cc)
        print(wk)
        mywhere.append('keyword=' + kw)
    # 遍历当前菜品分类信息并封存对应信息
    for vo in ulist:
        sob = Shop.objects.get(id=vo.shop_id)
        vo.shopname = sob.name
    # 执行分页处理
    pIndex = int(pIndex)
    page = Paginator(ulist, 5)  # 以每页5条数据分页
    maxpage = page.num_pages  # 获取最大页数
    # 判断当前页是否越界
    if pIndex > maxpage:
        pIndex = maxpage
    if pIndex < 1:
        pIndex = 1
    list2 = page.page(pIndex)  # 获取当前页
    plist = page.page_range  # 获取页码列表
    context = {"categorylist": list2, "plist": plist, "pIndex": pIndex, "maxpage": maxpage, "mywhere": mywhere}
    return render(request, "myadmin/category/index.html", context)

# 用于二级联动
def loadCategory(requset,uid):
    clist = Category.objects.filter(status__lt=9, shop_id=uid).values("id", "name")
    return JsonResponse({"data": list(clist)})

def add(request):  # 添加信息表单
    # 遍历当前菜品分类信息并封存对应信息
    name = []
    sob = Shop.objects.filter(status__lt=9)
    for i in sob:
        name.append(i.name)
    context = {'name': name}
    return render(request, "myadmin/category/add.html", context)


def insert(request):  # 执行信息添加
    try:
        ob = Category()
        sob = Shop.objects.filter(status__lt=9)
        for i in sob:
            if request.POST['shop_id'] == i.name:
                ob.shop_id = str(i.id)
        # ob.shop_id = request.POST['shop_id']
        ob.name = request.POST['name']

        ob.status = 1
        ob.create_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {'info': '添加成功'}
    except Exception as err:
        print(err)
        context = {'info': '添加失败'}
    return render(request, "myadmin/info.html", context)


def delete(request, uid=0):  # 执行删除信息
    try:
        ob = Category.objects.get(id=uid)
        print(ob.shop_id)
        ob.shop_id = str(ob.shop_id)
        ob.status = 9
        ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {'info': "删除成功！"}
    except Exception as err:
        print(err)
        context = {'info': "删除失败！"}
    return render(request, "myadmin/info.html", context)


def edit(request, uid=0):  # 加载信息编辑表单
    try:
        ob = Category.objects.get(id=uid)
        # 遍历当前菜品分类信息并封存对应信息
        name = []
        sob = Shop.objects.get(id=ob.shop_id)
        name.append(sob.name)
        sob = Shop.objects.filter(Q(status__lt=9) & (~Q(id=ob.shop_id)))
        for i in sob:
            print(i.name)
            name.append(i.name)
        context = {'category': ob, 'name': name}
        return render(request, "myadmin/category/edit.html", context)
    except Exception as err:
        print(err)
        context = {'info': '没有找到修改的信息'}
        return render(request, "myadmin/info.html", context)


def update(request, uid=0):  # 执行信息编辑
    try:
        ob = Category.objects.get(id=uid)
        sob = Shop.objects.filter(status__lt=9)
        print(request.POST['shop_id'])
        for i in sob:
            if request.POST['shop_id'] == i.name:
                ob.shop_id = str(i.id)
        ob.name = request.POST['name']
        ob.status = request.POST['status']
        ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {'info': '修改成功！'}
    except Exception as err:
        print(err)
        context = {'info': '修改失败！'}
    return render(request, "myadmin/info.html", context)
